package com.mt.skyhoist.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.provider.Settings.Secure;
import android.telephony.CellLocation;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.view.View;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static android.content.Context.ACTIVITY_SERVICE;

/**
 * 设备相关工具类.
 */
public class PhoneUtil
{

    protected static final String PREFS_FILE = "device_id.xml";
    protected static final String PREFS_DEVICE_ID = "device_id";
    /**
     * 设置铃音.
     * 
     * @param context
     *            the context
     * @param localUrl
     *            the local url
     * @param title
     *            the title
     * @param fileSize
     *            the file size
     * @param mimeType
     *            the mime type
     * @param playLength
     *            the play length
     */
    public static void settingRingertone(Context context, String localUrl, String title, String fileSize,
                                         String mimeType, String playLength)
    {
        try
        {
            if (StringUtil.isEmpty(localUrl) || !(new File(localUrl).exists()))
            {
                // DMG.showToast("歌曲文件不存在，不能设置铃声");
                return;
            }
            ContentValues cv = new ContentValues();
            Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            Uri newUri = null;
            Cursor cursor = context.getContentResolver().query(uri, new String[]
            { MediaStore.MediaColumns._ID }, MediaStore.MediaColumns.DATA + "=?", new String[]
            { localUrl }, null);
            try
            {
                if (cursor != null && cursor.moveToFirst())
                {
                    String _id = cursor.getString(0);
                    cv.put(MediaStore.Audio.Media.IS_RINGTONE, true);
                    // cv.put(MediaStore.Audio.Media.IS_MUSIC, true);
                    // 把需要设为铃声的歌曲插入铃声库
                    context.getContentResolver().update(uri, cv, MediaStore.MediaColumns.DATA + "=?", new String[]
                    { localUrl });
                    newUri = ContentUris.withAppendedId(uri, Long.valueOf(_id));
                } else
                {
                    ContentValues values = new ContentValues();
                    values.put(MediaStore.MediaColumns.DATA, localUrl);
                    values.put(MediaStore.MediaColumns.TITLE, title);
                    values.put(MediaStore.MediaColumns.SIZE, fileSize);
                    values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);// "audio/mp3"
                    // values.put(MediaStore.Audio.Media.ARTIST, song.get);
                    values.put(MediaStore.Audio.Media.DURATION, playLength);
                    values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
                    // values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
                    // values.put(MediaStore.Audio.Media.IS_ALARM, false);
                    // values.put(MediaStore.Audio.Media.IS_MUSIC, true);
                    // Toast.makeText(mContext, R.string.playlist_ringtone_error,
                    // Toast.LENGTH_SHORT).show();
                    Uri u = MediaStore.Audio.Media.getContentUriForPath(localUrl);
                    newUri = context.getContentResolver().insert(u, values);
                }
                // android.util.//LOG.d("SongAdapter", "1uri>>>>>>" +
                // Uri.parse(song.LocalUrl));
                RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
                // DMG.showToast("铃声设置成功");
            } catch (Exception e)
            {
                e.printStackTrace();
            } finally
            {
                if (cursor != null)
                {
                    cursor.close();
                }

            }
        } catch (Exception e)
        {
            // TODO: handle exception
        }
    }

    /**
     * 获取基站定位,不存在返回-1.<br>
     * <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
     * 
     * @return the gsm cell location
     */
    private static String getGsmCellLocation(Context context)
    {
        if (context != null)
        {
            try
            {
                TelephonyManager tm = (TelephonyManager) context.getApplicationContext().getSystemService(
                        Context.TELEPHONY_SERVICE);
                CellLocation gcl = tm.getCellLocation();
                if (gcl != null)
                {
                    if (gcl instanceof GsmCellLocation)
                    {
                        return "latitude:".concat(String.valueOf(((GsmCellLocation) gcl).getCid()))
                                .concat(",longitude:").concat(String.valueOf(((GsmCellLocation) gcl).getLac()));
                    } else if (gcl instanceof CdmaCellLocation)
                    {
                        return "latitude:".concat(String.valueOf(((CdmaCellLocation) gcl).getBaseStationLatitude()))
                                .concat(",longitude:")
                                .concat(String.valueOf(((CdmaCellLocation) gcl).getBaseStationLongitude()));
                    }

                }
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return "";
    }

    // private static Context getMCtx()
    // {
    // return RT.application;
    // }



    public static String phnfromSim = "";


    private static boolean isDoubleSimcard(Context context)
    {
        boolean isDouble = false;
        if (context != null)
        {
            Method method = null;
            Object result_0 = null;
            Object result_1 = null;
            try
            {
                isDouble = true;
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                // 只要在反射getSimStateGemini 这个函数时报了错就是单卡手机（这是我自己的经验，不一定全正确）
                method = TelephonyManager.class.getMethod("getSimStateGemini", new Class[]
                { int.class });
                // 获取SIM卡1
                result_0 = method.invoke(tm, new Object[]
                { Integer.valueOf(0) });
                // 获取SIM卡1
                result_1 = method.invoke(tm, new Object[]
                { Integer.valueOf(1) });
            } catch (SecurityException e)
            {
                isDouble = false;
                // DLOG.w("isDoubleSimcard", e);
                // e.printStackTrace();
                // System.out.println("1_ISSINGLETELEPHONE:"+e.toString());
            } catch (NoSuchMethodException e)
            {
                isDouble = false;
                // DLOG.w("isDoubleSimcard", e);
                // e.printStackTrace();
                // System.out.println("2_ISSINGLETELEPHONE:"+e.toString());
            } catch (IllegalArgumentException e)
            {
                isDouble = false;
                // DLOG.w("isDoubleSimcard", e);
                // e.printStackTrace();
            } catch (IllegalAccessException e)
            {
                isDouble = false;
                // DLOG.w("isDoubleSimcard", e);
                // e.printStackTrace();
            } catch (InvocationTargetException e)
            {
                isDouble = false;
                // DLOG.w("isDoubleSimcard", e);
                // e.printStackTrace();
            } catch (Exception e)
            {
                isDouble = false;
                // DLOG.w("isDoubleSimcard", e);
                // e.printStackTrace();
            }
            if (isDouble)
            {
                // 保存为双卡手机
                // editor.putBoolean(ISDOUBLE, true);
                // RT.PhoneInfo.isDoubleSimcard = true;
                // 保存双卡是否可用
                // 如下判断哪个卡可用.双卡都可以用
                if (result_0.toString().equals("5") && result_1.toString().equals("5"))
                {
                    // editor.putBoolean(SIMCARD_1, true);
                    // editor.putBoolean(SIMCARD_2, true);
                } else if (!result_0.toString().equals("5") && result_1.toString().equals("5"))
                {
                    // 卡二可用
                    // editor.putBoolean(SIMCARD_1, false);
                    // editor.putBoolean(SIMCARD_2, true);
                } else if (result_0.toString().equals("5") && !result_1.toString().equals("5"))
                {// 卡一可用

                    // editor.putBoolean(SIMCARD_1, true);
                    // editor.putBoolean(SIMCARD_2, false);
                } else
                {// 两个卡都不可用(飞行模式会出现这种种情况)
                 // editor.putBoolean(SIMCARD_1, false);
                 // editor.putBoolean(SIMCARD_2, false);
                }
            }

        }
        return isDouble;
    }

    /**
     * 进入系统默认短信页面发送短信，给一个人或多个人
     * 
     * @param context
     * @param phoneNumbers
     *            短话号码的List
     * @param sms_body
     *            要发送的短信内容
     */
    public static void sendSMS(Context context, List<String> phoneNumbers, String sms_body)
    {
        try
        {
            // 短信发送多个号码的分隔符 话说三星手机的分隔符是【,】
            String separator = ";";
            if (Build.MANUFACTURER.equalsIgnoreCase("samsung"))
                separator = ",";

            String smsto = "smsto:";
            for (int i = 0; i < phoneNumbers.size(); i++)
            {
                if (i != 0)
                    smsto = smsto.concat(separator);
                smsto = smsto.concat(phoneNumbers.get(i));
            }
            // smsto = smsto.concat(phnlist.get(0));
            Uri smsToUri = Uri.parse(smsto);
            Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
            intent.putExtra("sms_body", sms_body);
            context.startActivity(intent);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * Gets the device id.
     * 
     * @return the device id
     */
    private static String getDeviceId(Context context)
    {
        String android_id = "";
        if (context != null)
        {
            android_id = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
        }
        return android_id;
    }

    /**
     * cpu序列号
     * 
     * @return the serial number
     */
    public static String getSerialNumber()
    {
        String serial = null;
        try
        {
            if (hasHoneycomb())
            {
                try
                {
                    serial = getSerialNum3();
                } catch (Exception e)
                {
                }
            }
            if (StringUtil.isEmpty(serial))
            {
                try
                {
                    Class<?> c = Class.forName("android.os.SystemProperties");
                    Method get = c.getMethod("get", String.class);
                    serial = (String) get.invoke(c, "ro.serialno");
                } catch (Exception e)
                {
                }
            }
            if (StringUtil.isEmpty(serial))
            {
                try
                {
                    serial = getCPUSerial();
                } catch (Exception e)
                {
                }
            }
        } catch (Exception ignored)
        {
        }
        return serial;
    }

    @SuppressLint("NewApi")
    public static String getSerialNum3()
    {
        return Build.SERIAL;
    }

    /**
     * 获取CPU序列号
     * 
     * @return CPU序列号(16位) 读取失败为"0000000000000000"
     */
    public static String getCPUSerial()
    {
        String str = "", strCPU = "", cpuAddress = "0000000000000000";
        try
        {
            // 读取CPU信息
            Process pp = Runtime.getRuntime().exec("cat /proc/cpuinfo");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            // 查找CPU序列号
            for (int i = 1; i < 100; i++)
            {
                str = input.readLine();
                if (str != null)
                {
                    // 查找到序列号所在行
                    if (str.indexOf("Serial") > -1)
                    {
                        // 提取序列号
                        strCPU = str.substring(str.indexOf(":") + 1, str.length());
                        // 去空格
                        cpuAddress = strCPU.trim();
                        break;
                    }
                } else
                {
                    // 文件结尾
                    break;
                }
            }
        } catch (IOException ex)
        {
            // 赋予默认值
        }
        return cpuAddress;
    }

    /**
     * 检查耳机
     * 
     * @return
     */
    public static boolean checkHeadSetState()
    {
        String HEADSET_STATE_PATH = "/sys/class/switch/h2w/state";
        FileReader file = null;
        try
        {
            file = new FileReader(HEADSET_STATE_PATH);
            char[] buffer = new char[1024];
            int len = file.read(buffer, 0, 1024);
            int headsetState = Integer.valueOf((new String(buffer, 0, len)).trim());
            // DLOG.e("headSet", "is useing handSet >>" + (headsetState == 1));
            if (headsetState == 1)
            {
                return true;
            } else
            {
                return false;
            }
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
            return false;
        } catch (Exception e)
        {
            e.printStackTrace();
            return false;
        } finally
        {
            if (file != null)
            {
                try
                {
                    file.close();
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    @SuppressLint("NewApi")
    public static void enableStrictMode()
    {
        try
        {
            if (hasGingerbread())
            {
                android.os.StrictMode.ThreadPolicy.Builder threadPolicyBuilder = new android.os.StrictMode.ThreadPolicy.Builder()
                        .detectAll().penaltyLog();
                android.os.StrictMode.VmPolicy.Builder vmPolicyBuilder = new android.os.StrictMode.VmPolicy.Builder()
                        .detectAll().penaltyLog();

                if (hasHoneycomb())
                {
                    threadPolicyBuilder.penaltyFlashScreen();
                    // vmPolicyBuilder.setClassInstanceLimit(ImageGridActivity.class, 1).setClassInstanceLimit(
                    // ImageDetailActivity.class, 1);
                }
                android.os.StrictMode.setThreadPolicy(threadPolicyBuilder.build());
                android.os.StrictMode.setVmPolicy(vmPolicyBuilder.build());
            }
        } catch (Throwable e)
        {
            e.printStackTrace();
        }
    }

    public static class MemInfo
    {
        public long availMem;
        public long threshold;
        public boolean lowMemory;
        public long maxMemory;// JVM
        public long freeMemory;// JVM

        public String toString()
        {
            return "".concat(String.valueOf(availMem)).concat(":").concat(String.valueOf(freeMemory)).concat(":")
                    .concat(String.valueOf(maxMemory)).concat(":").concat(String.valueOf(threshold)).concat(":")
                    .concat(String.valueOf(lowMemory));
        }
    }

    public static MemInfo availidMem(Context ct)
    {

        MemInfo mem = new MemInfo();
        try
        {
            mem.maxMemory = Runtime.getRuntime().maxMemory();
            mem.freeMemory = Runtime.getRuntime().freeMemory();
            ActivityManager am = (ActivityManager) ct.getSystemService(ACTIVITY_SERVICE);
            MemoryInfo mi = new MemoryInfo();
            am.getMemoryInfo(mi);
            mem.availMem = mi.availMem;
            mem.threshold = mi.threshold;
            mem.lowMemory = mi.lowMemory;
            // if (RT.DEBUG)
            // {
            // Log.e("max", "mi.availMem:" + mem.availMem + "mi.threshold:" + mem.threshold + "mi.lowMemory:"
            // + mem.lowMemory + "Runtime.getRuntime().maxMemory():" + mem.maxMemory
            // + "Runtime.getRuntime().freeMemory():" + mem.freeMemory);
            // }
        } catch (Throwable e)
        {
            e.printStackTrace();
        }
        return mem;

    }

    public static String getTotalMemory(Context context)
    {
        String str1 = "/proc/meminfo";// 系统内存信息文件
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;

        try
        {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
            str2 = localBufferedReader.readLine();// 读取meminfo第一行，系统总内存大小

            arrayOfString = str2.split("//s+");
            for (String num : arrayOfString)
            {
//                DLOG.i(str2, num + "/t");
            }

            initial_memory = Long.valueOf(arrayOfString[1]) / 1024;// 获得系统总内存，单位是KB，乘以1024转换为Byte
            localBufferedReader.close();
        } catch (IOException e)
        {
        }
        return Formatter.formatFileSize(context, initial_memory);// Byte转换为KB或者MB，内存大小规格化
    }


    // 获取指定Activity的截屏，保存到png文件
    public static Bitmap takeScreenShot(Activity activity)
    {
        // View是你需要截图的View
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap b1 = view.getDrawingCache();

        // 获取状态栏高度
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;
        // DLOG.i("TAG", "" + statusBarHeight);

        // 获取屏幕长和高
        int width = 0;
        int height = 0;
        int[] size = getPhoneScreenSize(activity);
        width = size[0];
        height = size[1];
        // 去掉标题栏
        // Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
        Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
        view.destroyDrawingCache();
        return b;
    }

    private static int[] ScreenSize = new int[]
    { 0, 0 };

    /**
     * 获取屏幕宽高
     * 
     * @param activity
     *            the activity
     * @return the phone screen size
     */
    @SuppressLint("NewApi")
    public static int[] getPhoneScreenSize(Activity activity)
    {
        if (ScreenSize[0] > 0 && ScreenSize[1] > 0)
        {
            return ScreenSize;
        }
        int width = 0;
        int height = 0;
        if (PhoneUtil.hasHoneycombMR2())
        {
            Point size = new Point();
            activity.getWindowManager().getDefaultDisplay().getSize(size);
            width = size.x;
            height = size.y;
        } else
        {
            width = activity.getWindowManager().getDefaultDisplay().getWidth();
            height = activity.getWindowManager().getDefaultDisplay().getHeight();
        }
        ScreenSize[0] = width;
        ScreenSize[1] = height;
        return ScreenSize;
    }

    public static int dipToPixel(float dp, Context mContext)
    {
        float scale = mContext.getResources().getDisplayMetrics().density;
        int pixel = (int) (dp * scale + 0.5f);
        return pixel;
    }

    public static float pixelToDip(int pixel, Context mContext)
    {
        float scale = mContext.getResources().getDisplayMetrics().density;
        float dp = (float) (pixel - 0.5f) / scale;
        return dp;
    }

    public interface ScreenDifine
    {
        public static final int LowDpi240 = 1;
        public static final int midDpi480 = 2;
        public static final int highDpi720 = 3;
    }

    public static int getPhoneScreenDifine(Activity activity)
    {
        int size[] = getPhoneScreenSize(activity);
        int min = Math.min(size[0], size[1]);
        int ret;
        if (min >= 240 && min < 480)
        {
            ret = ScreenDifine.LowDpi240;
        } else if (min >= 480 && min < 720)
        {
            ret = ScreenDifine.midDpi480;
        } else if (min >= 720)
        {
            ret = ScreenDifine.highDpi720;
        } else
        {
            ret = ScreenDifine.LowDpi240;
        }

        return ret;
    }

    public static boolean isMIUI()
    {
        String line;
        BufferedReader input = null;
        try
        {
            Process p = Runtime.getRuntime().exec("getprop ro.miui.ui.version.name");
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
            // DLOG.d("cccmax", "isMIUI : name = " + line);
        } catch (IOException ex)
        {
            return Build.MANUFACTURER.equalsIgnoreCase("Xiaomi");
        } finally
        {
            if (input != null)
            {
                try
                {
                    input.close();
                } catch (IOException e)
                {
                    // Log.e(TAG, "Exception while closing InputStream", e);
                }
            }
        }
        return !StringUtil.isEmpty(line);
    }

    public static int getMIUIVersion()
    {
        String line;
        BufferedReader input = null;
        try
        {
            Process p = Runtime.getRuntime().exec("getprop ro.miui.ui.version.name");
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
//            DLOG.i("getMIUIVersion", line);
        } catch (IOException ex)
        {
            return Build.MANUFACTURER.equalsIgnoreCase("Xiaomi") ? 0 : -1;
        } finally
        {
            if (input != null)
            {
                try
                {
                    input.close();
                } catch (IOException e)
                {
                }
            }
        }
        int ret = -1;
        if (StringUtil.isEmpty(line))
            ret = -1;
        else if (line.length() >= 2)
        {
            try
            {
                ret = Integer.parseInt(line.substring(1));
            } catch (Exception e)
            {
                ret = -1;
            }
        }
        return ret;
    }

    public static boolean isNotLowDpiScreen(Activity context)
    {
        return PhoneUtil.getPhoneScreenDifine(context) > ScreenDifine.midDpi480;
    }

    public static boolean hasFroyo()
    {

        return Build.VERSION.SDK_INT >= 8;// Build.VERSION_CODES.FROYO;
    }

    public static boolean hasGingerbread()
    {
        return Build.VERSION.SDK_INT >= 9;// Build.VERSION_CODES.GINGERBREAD;
    }

    public static boolean hasGingerbreadMR1()
    {
        return Build.VERSION.SDK_INT >= 10;// Build.VERSION_CODES.GINGERBREAD_MR1;
    }

    public static boolean hasHoneycomb()
    {
        return Build.VERSION.SDK_INT >= 11; // Build.VERSION_CODES.HONEYCOMB;
    }

    public static boolean hasHoneycombMR1()
    {
        return Build.VERSION.SDK_INT >= 12; // Build.VERSION_CODES.HONEYCOMB_MR1;
    }

    public static boolean hasHoneycombMR2()
    {
        return Build.VERSION.SDK_INT >= 13; // Build.VERSION_CODES.HONEYCOMB_MR1;
    }

    public static boolean hasIceCreamSandwich()
    {
        return Build.VERSION.SDK_INT >= 14;// Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1;
    }

    public static boolean hasIceCreamSandwichMR1()
    {
        return Build.VERSION.SDK_INT >= 15;// Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1;
    }

    public static boolean hasJellyBean()
    {
        return Build.VERSION.SDK_INT >= 16;
    }

    public static boolean hasJellyBeanMR1()
    {
        // Build.VERSION_CODES.
        return Build.VERSION.SDK_INT >= 17;
    }

    public static boolean hasJellyBeanMR2()
    {
        return Build.VERSION.SDK_INT >= 18;
    }

    public static boolean isVerionEngouth()
    {
        if (Build.VERSION.RELEASE.compareTo("4.0") < 0)
        {
            return false;
        }
        return true;
    }

    public static int getWindowWidth(Context context)
    {
        DisplayMetrics dm = new DisplayMetrics();
        dm = context.getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    public static int getWindowHeight(Context context)
    {
        DisplayMetrics dm = new DisplayMetrics();
        dm = context.getResources().getDisplayMetrics();
        return dm.heightPixels;
    }

    /**
     * 通过包名获取应用程序的名称。
     * 
     * @param context
     *            Context对象。
     * @param packageName
     *            包名。
     * @return 返回包名所对应的应用程序的名称。
     */
    public static String getProgramNameByPackageName(Context context, String packageName)
    {
        PackageManager pm = context.getPackageManager();
        String name = null;
        try
        {
            name = pm.getApplicationLabel(pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA)).toString();
        } catch (NameNotFoundException e)
        {
            e.printStackTrace();
        }
        return name;
    }

    public static ComponentName getTopComponentName(Context context)
    {
        ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentName = taskInfo.get(0).topActivity;
        return componentName;
    }


    public static boolean getAllApps(Context context, String packagename) {
        PackageManager pManager = context.getPackageManager();
        ArrayList<String> names = new ArrayList<String>();
        //获取手机内所有应用  
        List<PackageInfo> paklist = pManager.getInstalledPackages(0);
        for (int i = 0; i < paklist.size(); i++) {  
            PackageInfo pak = (PackageInfo) paklist.get(i);
            if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0) {  
                // customs applications
                String name = pak.applicationInfo.loadLabel(context.getPackageManager()).toString();
                if(pak.packageName.equals(packagename))
                {
                    return true;
                }
            }  
        }  
        return false;  
    }
    
    
    public static boolean getScreenOrientation(Context context)
    {
        Configuration mConfiguration = context.getResources().getConfiguration();
        int ori = mConfiguration.orientation ; 

        if(ori == mConfiguration.ORIENTATION_LANDSCAPE){
            return true;
        }else if(ori == mConfiguration.ORIENTATION_PORTRAIT){
            return false;
        }
        return false;
    }
    
    public static boolean isServiceRunning(Context mContext, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager)
        mContext.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList
        = activityManager.getRunningServices(30);
       if (!(serviceList.size()>0)) {
            return false;
        }
        for (int i=0; i<serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }
    
    public static String getPackgeName(Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        String packageName = cn.getPackageName();
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(
                    packageName, 0);
            String appName = packageInfo.applicationInfo.loadLabel(
                    context.getPackageManager()).toString();
            return packageName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return packageName;
    }
    

    public static String getThumbImageUrl(int mode, String url, int width, int height)
    {
        if(mode==1||mode==2&&width!=0&&height!=0)
        {
            return url+"?imageView/"+mode+"/w/"+width+"/h/"+height;
        }
        return url;
    }
    
    public static String getOnlyCode(Context context)
    {
        UUID uuid;
        SharedPreferences prefs = context.getSharedPreferences(PREFS_FILE, 0);
        String id = prefs.getString(PREFS_DEVICE_ID, null );

        if (id != null) {
            // Use the ids previously computed and stored in the prefs file
            uuid = UUID.fromString(id);

        } else {

            final String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);

            // Use the Android ID unless it's broken, in which case fallback on deviceId,
            // unless it's not available, then fallback on a random number which we store
            // to a prefs file
            try {
                if (!"9774d56d682e549c".equals(androidId)) {
                    uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
                } else {
                    final String deviceId = ((TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE )).getDeviceId();
                    uuid = deviceId!=null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID();
                }
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }

            // Write the value out to the prefs file
            prefs.edit().putString(PREFS_DEVICE_ID, uuid.toString() ).commit();
        }
        return uuid.toString();
    }


    public static byte[] int2byte(int res) {
        byte[] targets = new byte[4];

        targets[3] = (byte) (res & 0xff);// 最低位
        targets[2] = (byte) ((res >> 8) & 0xff);// 次低位
        targets[1] = (byte) ((res >> 16) & 0xff);// 次高位
        targets[0] = (byte) (res >>> 24);// 最高位,无符号右移。
        return targets;
    }
//    public static byte[] int2byte(int res) {
//        byte[] targets = new byte[4];
//
//        targets[0] = (byte) (res & 0xff);// 最低位
//        targets[1] = (byte) ((res >> 8) & 0xff);// 次低位
//        targets[2] = (byte) ((res >> 16) & 0xff);// 次高位
//        targets[3] = (byte) (res >>> 24);// 最高位,无符号右移。
//        return targets;
//    }

    public static int byte2int(byte[] res) {
// 一个byte数据左移24位变成0x??000000，再右移8位变成0x00??0000

//        int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00) // | 表示安位或
//                | ((res[2] << 24) >>> 8) | (res[3] << 24);
//        return targets;
        int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00) // | 表示安位或
                | ((res[2] << 24) >>> 8) | (res[3] << 24);
        return targets;
    }


    /**
     * 判断app是否处于前台
     * @param context
     * @return
     */
    public static boolean isRunningForeground (Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcessInfos = manager.getRunningAppProcesses();
        if(appProcessInfos == null || appProcessInfos.isEmpty()){
            return false;
        }
        for(ActivityManager.RunningAppProcessInfo info : appProcessInfos){
            //当前应用处于运行中，并且在前台
            if(info.processName.equals(context.getPackageName()) && info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
                return true;
            }
        }
        return false;
    }
}